package cn.edu.ldu.views.login;

import cn.edu.ldu.entity.UserEntity;
import cn.edu.ldu.protocol.Protocol;
import cn.edu.ldu.util.Consts;
import cn.edu.ldu.util.L;
import cn.edu.ldu.util.Translate;
import com.alibaba.fastjson.JSON;

import javax.swing.*;
import javax.xml.crypto.Data;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.MouseEvent;
import java.io.IOException;
import java.lang.reflect.Constructor;
import java.lang.reflect.InvocationTargetException;
import java.net.*;
import java.text.SimpleDateFormat;
import java.util.Date;

/**
 *
 * @author DYZ
 */
public class RegisterUI extends javax.swing.JPanel {

    /**
     * Creates new form RegisterUI
     */
    public RegisterUI() {
        initComponents();
        this.setSize(Consts.L_CONTENT_WIDTH,Consts.L_CONTENTS_HEIGHT_OPEN);
        this.setVisible(true);
    }

    /**
     * This method is called from within the constructor to initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is always
     * regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">
    private void initComponents() {

        jLabel1 = new javax.swing.JLabel();
        btnPanel = new javax.swing.JPanel();
        btnReset = new javax.swing.JButton();
        btnRegister = new javax.swing.JButton();
        mainPanel = new javax.swing.JPanel();
        labUsername = new javax.swing.JLabel();
        txtUsername = new javax.swing.JTextField();
        labUserpass1 = new javax.swing.JLabel();
        txtUserpass1 = new javax.swing.JTextField();
        labSurepass = new javax.swing.JLabel();
        txtSurepass = new javax.swing.JTextField();
        labPhone = new javax.swing.JLabel();
        txtPhone = new javax.swing.JTextField();

        jLabel1.setText("jLabel1");

        setBorder(javax.swing.BorderFactory.createTitledBorder("注册账户"));
        setLayout(new java.awt.BorderLayout());

        btnReset.setText("重置");
        btnReset.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnResetMouseClicked(evt);
            }
        });

        btnRegister.setText("确定注册");
        btnRegister.addMouseListener(new java.awt.event.MouseAdapter() {
            public void mouseClicked(java.awt.event.MouseEvent evt) {
                btnRegisterMouseClicked(evt);
            }
        });

        javax.swing.GroupLayout btnPanelLayout = new javax.swing.GroupLayout(btnPanel);
        btnPanel.setLayout(btnPanelLayout);
        btnPanelLayout.setHorizontalGroup(
                btnPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(btnPanelLayout.createSequentialGroup()
                                .addGap(44, 44, 44)
                                .addComponent(btnReset, javax.swing.GroupLayout.PREFERRED_SIZE, 93, javax.swing.GroupLayout.PREFERRED_SIZE)
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 71, Short.MAX_VALUE)
                                .addComponent(btnRegister)
                                .addGap(100, 100, 100))
        );
        btnPanelLayout.setVerticalGroup(
                btnPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(btnPanelLayout.createSequentialGroup()
                                .addContainerGap()
                                .addGroup(btnPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(btnReset)
                                        .addComponent(btnRegister))
                                .addContainerGap(javax.swing.GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE))
        );

        add(btnPanel, java.awt.BorderLayout.PAGE_END);

        labUsername.setText("设置昵称：");

        labUserpass1.setText("设置密码：");

        labSurepass.setText("确定密码：");

        labPhone.setText("手机号码：");

        javax.swing.GroupLayout mainPanelLayout = new javax.swing.GroupLayout(mainPanel);
        mainPanel.setLayout(mainPanelLayout);
        mainPanelLayout.setHorizontalGroup(
                mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(mainPanelLayout.createSequentialGroup()
                                .addGap(41, 41, 41)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING, false)
                                        .addGroup(mainPanelLayout.createSequentialGroup()
                                                .addComponent(labPhone)
                                                .addGap(18, 18, 18)
                                                .addComponent(txtPhone))
                                        .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                                                .addGroup(mainPanelLayout.createSequentialGroup()
                                                        .addComponent(labUsername)
                                                        .addGap(18, 18, 18)
                                                        .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addGroup(mainPanelLayout.createSequentialGroup()
                                                        .addComponent(labSurepass)
                                                        .addGap(18, 18, 18)
                                                        .addComponent(txtSurepass, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))
                                                .addGroup(javax.swing.GroupLayout.Alignment.TRAILING, mainPanelLayout.createSequentialGroup()
                                                        .addComponent(labUserpass1)
                                                        .addGap(18, 18, 18)
                                                        .addComponent(txtUserpass1, javax.swing.GroupLayout.PREFERRED_SIZE, 158, javax.swing.GroupLayout.PREFERRED_SIZE))))
                                .addContainerGap(52, Short.MAX_VALUE))
        );
        mainPanelLayout.setVerticalGroup(
                mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.LEADING)
                        .addGroup(mainPanelLayout.createSequentialGroup()
                                .addGap(25, 25, 25)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(labUsername)
                                        .addComponent(txtUsername, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addPreferredGap(javax.swing.LayoutStyle.ComponentPlacement.RELATED, 15, Short.MAX_VALUE)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(labPhone)
                                        .addComponent(txtPhone, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(18, 18, 18)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(txtUserpass1, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE)
                                        .addComponent(labUserpass1))
                                .addGap(18, 18, 18)
                                .addGroup(mainPanelLayout.createParallelGroup(javax.swing.GroupLayout.Alignment.BASELINE)
                                        .addComponent(labSurepass)
                                        .addComponent(txtSurepass, javax.swing.GroupLayout.PREFERRED_SIZE, javax.swing.GroupLayout.DEFAULT_SIZE, javax.swing.GroupLayout.PREFERRED_SIZE))
                                .addGap(23, 23, 23))
        );

        add(mainPanel, BorderLayout.NORTH);
    }// </editor-fold>

    /**
     * 重置按钮
     * 所有的标签都为空
     * @param evt
     */
    private void btnResetMouseClicked(MouseEvent evt){
        txtPhone.setText("");
        txtSurepass.setText("");
        txtUsername.setText("");
        txtUserpass1.setText("");
    }

    /**
     * 确定注册
     * 需要提交 昵称 手机号码 密码
     * 确定密码需要和设置密码一致
     */
    private void btnRegisterMouseClicked(MouseEvent evt){
        //1、判定其中是否为空
        if((txtPhone.getText().trim().equals(""))||(txtSurepass.getText().trim().equals(""))||(txtUsername.getText().trim().equals(""))||txtUserpass1.getText().trim().equals("")){
            JOptionPane.showMessageDialog(null, "请将信息填写完整", "提示", JOptionPane.ERROR_MESSAGE);
        }else{
            //2、判定设置密码和确定密码是否一致,一致就向下走，不然就提示
            if (txtUserpass1.getText().trim().equals(txtSurepass.getText().trim())){
                //3、询问信息是否正确，以及是否注册
                int res = JOptionPane.showConfirmDialog(null, "确定信息是否无误", "是否继续", JOptionPane.YES_NO_OPTION);
                if (res == JOptionPane.YES_OPTION) {
                    //确定注册
                    String username = txtUsername.getText().trim();
                    String mobile = txtPhone.getText().trim();
                    String password = txtUserpass1.getText().trim();
                    //提交给服务器
                    InetAddress remoteAddr = null;
                    try {
                        remoteAddr = InetAddress.getByName(Consts.ipv4);
                        //创建UDP套件字
                        DatagramSocket clientSocket = null;
                        clientSocket = new DatagramSocket();
                        clientSocket.setSoTimeout(5000);

                        //获取当前时间
                        Date date = new Date();
                        //构造用户注册信息
                        Protocol protocol = new Protocol();
                        protocol.setKey("Register");
                        UserEntity ue = new UserEntity();
                        ue.setUsername(username);
                        ue.setMobile(mobile);
                        ue.setPassword(password);
                        ue.setCreateTime(date);
//                        ue.setPort(Consts.port);

                        //转字符
                        protocol.setData(JSON.toJSONString(ue));
                        byte[] data = Translate.ObjectToByte(protocol);

                        //定义注册报文
                        DatagramPacket packet = new DatagramPacket(data,data.length,remoteAddr,Consts.port);

                        //发送报文
                        clientSocket.send(packet);
                        L.OK(packet,RegisterUI.class);

                        //从服务器得到令牌
                        byte[] backData = new byte[8096];
                        DatagramPacket backPacket = new DatagramPacket(backData,backData.length,remoteAddr,Consts.port);

                        //得到指令
                        clientSocket.receive(backPacket);
                        L.OK(backPacket,RegisterUI.class);

                        Protocol pro = (Protocol) Translate.ByteToObject(backPacket.getData());

                        //解决视图问题
                        Class cls = Class.forName("cn.edu.ldu.protocol."+pro.getKey());
                        //registerSuccess || fail
                        Constructor con = cls.getConstructor(Protocol.class);
                        con.newInstance(pro);
                     } catch (IOException | ClassNotFoundException | NoSuchMethodException | IllegalAccessException | InstantiationException | InvocationTargetException e) {
                        e.printStackTrace();
                    }
                } else {
                    return;
                }

            }else {
              //设置密码和确定密码不一致
                JOptionPane.showMessageDialog(null, "请将设置密码和确定密码填写一致", "提示", JOptionPane.ERROR_MESSAGE);
            }
        }
    }

    // Variables declaration - do not modify
    private javax.swing.JPanel btnPanel;
    private javax.swing.JButton btnRegister;
    private javax.swing.JButton btnReset;
    private javax.swing.JLabel jLabel1;
    private javax.swing.JLabel labPhone;
    private javax.swing.JLabel labSurepass;
    private javax.swing.JLabel labUsername;
    private javax.swing.JLabel labUserpass1;
    private javax.swing.JPanel mainPanel;
    private javax.swing.JTextField txtPhone;
    private javax.swing.JTextField txtSurepass;
    private javax.swing.JTextField txtUsername;
    private javax.swing.JTextField txtUserpass1;
    // End of variables declaration
}